package com.pond.file.controller;

import com.pond.file.domain.UploadTosResult;
import com.pond.file.utils.TosService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.pond.common.core.domain.R;
import com.pond.common.core.utils.file.FileUtils;
import com.pond.file.service.ISysFileService;
import com.pond.system.api.domain.SysFile;

import java.io.IOException;

/**
 * 文件请求处理
 * 
 * @author ruoyi
 */
@RestController
public class SysFileController
{
    private static final Logger log = LoggerFactory.getLogger(SysFileController.class);

    @Autowired
    private ISysFileService sysFileService;

    @Autowired
    private TosService tosService;

    /**
     * 文件上传请求
     */
    @PostMapping("upload")
    public R<SysFile> upload(MultipartFile file)
    {
        try
        {
            // 上传并返回访问地址
            String url = sysFileService.uploadFile(file);
            SysFile sysFile = new SysFile();
            sysFile.setName(FileUtils.getName(url));
            sysFile.setUrl(url);
            return R.ok(sysFile);
        }
        catch (Exception e)
        {
            log.error("上传文件失败", e);
            return R.fail(e.getMessage());
        }
    }

    /**
     * 文件上传到oss
     * @
     */
    @PostMapping("upload/oss")
    public R<UploadTosResult> uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        return R.ok(tosService.uploadToTos(file)); // 返回文件的完整访问地址
    }
    
    /**
     * 头像上传到OSS (返回SysFile格式以兼容现有接口)
     */
    @PostMapping("upload/avatar")
    public R<SysFile> uploadAvatar(@RequestParam("file") MultipartFile file) throws IOException {
        try {
            UploadTosResult tosResult = tosService.uploadToTos(file);
            SysFile sysFile = new SysFile();
            sysFile.setName(tosResult.getFileName());
            sysFile.setUrl(tosResult.getUrl());
            return R.ok(sysFile);
        } catch (Exception e) {
            log.error("上传头像失败", e);
            return R.fail(e.getMessage());
        }
    }
}